import { defineStore } from 'pinia'
import { store } from '@/stores'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { LocaleDropdownType } from '@/types/localeDropdown'

const { wsCache } = useCache()

// 语言字符串与element plus语言对象的映射
// js中对象的键名加不加引号是一样的，如果没有加引号，js会自动将其转换为字符串，{en: en}、{en}、{'en': en}都是相同的
const elLocaleMap = {
  'zh-CN': zhCn,
  en: en
}

interface LocaleState {
  currentLocale: LocaleDropdownType // 当前应用的语言
  localeMap: LocaleDropdownType[] // 可选语言列表
}

// 使用选项式写法
export const useLocaleStore = defineStore('locales', {
  state: (): LocaleState => {
    return {
      currentLocale: {
        lang: wsCache.get(CACHE_KEY.LANG) || 'zh-CN',
        elLocale: elLocaleMap[wsCache.get(CACHE_KEY.LANG) || 'zh-CN']
      },
      localeMap: [
        {
          lang: 'zh-CN',
          name: '简体中文'
        },
        {
          lang: 'en',
          name: 'English'
        }
      ]
    }
  },
  getters: {
    getCurrentLocale(): LocaleDropdownType {
      return this.currentLocale
    },
    getLocaleMap(): LocaleDropdownType[] {
      return this.localeMap
    }
  },
  actions: {
    setCurrentLocale(locale: LocaleDropdownType) {
      this.currentLocale.lang = locale?.lang
      this.currentLocale.elLocale = elLocaleMap[locale?.lang]
      wsCache.set(CACHE_KEY.LANG, locale?.lang)
    }
  },
  persist: false // 默认不会持久化
})

/**
 * useLocaleStore()用于vue setup或context上下文环境中
 * useLocaleStoreWithOut()用于非vue setup上下文环境中
 */
export const useLocaleStoreWithOut = () => {
  return useLocaleStore(store)
}
